/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.cef.generator.apiGenerator.dataType.entityInterface.propertyInfo;

import com.inspur.edp.bef.bizentity.GspBusinessEntity;
import com.inspur.edp.caf.generator.baseInfo.AnnotationInfo;
import com.inspur.edp.caf.generator.baseInfo.PropertyGenerateInfo;
import com.inspur.edp.caf.generator.baseInfo.TypeInfo;
import com.inspur.edp.caf.generator.property.ClassPropertyGenerator;
import com.inspur.edp.caf.generator.property.PropertyGenerator;
import com.inspur.edp.cef.designtime.api.IGspCommonField;
import com.inspur.edp.cef.designtime.api.element.ForeignKeyConstraintType;
import com.inspur.edp.cef.designtime.api.element.GspAssociation;
import com.inspur.edp.cef.generator.DotNetToJavaStringHelper;
import com.inspur.edp.cef.generator.apiGenerator.dataType.entityInterface.DataTypeInterfaceGeneratorContext;
import com.inspur.edp.cef.generator.overall.Utils;
import com.inspur.edp.cef.spi.entity.AssociationEnableState;
import com.inspur.edp.cef.spi.entity.AssociationInfo;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.MetadataHeader;
import com.inspur.edp.lcm.metadata.api.service.RefCommonService;
import java.util.ArrayList;

import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.core.dom.Modifier.ModifierKeyword;

public class PropertyInfoAssociationGenerator extends ClassPropertyGenerator {
  private DataTypeInterfaceGeneratorContext parentContext;
  private IGspCommonField field;

  public PropertyInfoAssociationGenerator(
      DataTypeInterfaceGeneratorContext parentContext, IGspCommonField field) {
    this.parentContext = parentContext;
    this.field = field;
  }

  @Override
  protected boolean isGetterOverride() {
    return true;
  }

  @Override
  protected ArrayList<ModifierKeyword> getGetterAccessModifier() {
    return new java.util.ArrayList<ModifierKeyword>(
        java.util.Arrays.asList(
            new ModifierKeyword[] {
                ModifierKeyword.PUBLIC_KEYWORD
            }));
  }


  @Override
  protected ArrayList<ModifierKeyword> getSetterAccessModifier() {
    return null;
  }

  @Override
  protected String getPropertyName() {
    return "AssociationInfo";
  }

//  @Override
//  protected PropertyGenerateInfo createPropertyInfo() {
//    return new PropertyGenerateInfo();
//  }

  @Override
  protected TypeInfo getPropertyType() {
    return new TypeInfo("AssociationInfo");
  }

  @Override
  protected String getFieldName() {
    return "private" + getPropertyName();
  }

  @Override
  protected org.eclipse.jdt.core.dom.Block buildGetMethodBody() {

    GspAssociation association = field.getChildAssociations().get(0);
    String[] info = parseRef(association);
    Block rez = ast.newBlock();

    String resultVarName = "result";
    VariableDeclarationFragment declarationFragment = ast.newVariableDeclarationFragment();
    declarationFragment.setName(ast.newSimpleName(resultVarName));
    ClassInstanceCreation creationStat = ast.newClassInstanceCreation();
    creationStat.setType(ast.newSimpleType(ast.newName(AssociationInfo.class.getName())));
    declarationFragment.setInitializer(creationStat);
    VariableDeclarationStatement variableDeclarationStatement=ast.newVariableDeclarationStatement(declarationFragment);

    variableDeclarationStatement.setType(
        ast.newSimpleType(ast.newName(AssociationInfo.class.getName())));
    rez.statements().add(variableDeclarationStatement);

    MethodInvocation setConfigExpr = ast.newMethodInvocation();
    setConfigExpr.setExpression(ast.newSimpleName(resultVarName));
    StringLiteral configValue = ast.newStringLiteral();
    configValue.setLiteralValue(info[0]);
    setConfigExpr.setName(ast.newSimpleName("setConfig"));
    setConfigExpr.arguments().add(configValue);
    ExpressionStatement expressionStatement=ast.newExpressionStatement(setConfigExpr);
    rez.statements().add(expressionStatement);

    MethodInvocation setNodeCodeExpr = ast.newMethodInvocation();
    setNodeCodeExpr.setExpression(ast.newSimpleName(resultVarName));
    StringLiteral nodeCodeValue = ast.newStringLiteral();
    nodeCodeValue.setLiteralValue(info[1]);
    setNodeCodeExpr.setName(ast.newSimpleName("setNodeCode"));
    setNodeCodeExpr.arguments().add(nodeCodeValue);
    ExpressionStatement expressionStatement1=ast.newExpressionStatement(setNodeCodeExpr);
    rez.statements().add(expressionStatement1);

    MethodInvocation setMainCodeExpr = ast.newMethodInvocation();
    setMainCodeExpr.setExpression(ast.newSimpleName(resultVarName));
    StringLiteral mainCodeValue = ast.newStringLiteral();
    mainCodeValue.setLiteralValue(info[2]);
    setMainCodeExpr.setName(ast.newSimpleName("setMainCode"));
    setMainCodeExpr.arguments().add(mainCodeValue);
    ExpressionStatement expressionStatement2=ast.newExpressionStatement(setMainCodeExpr);
    rez.statements().add(expressionStatement2);

    MethodInvocation setEnableStateExpr = ast.newMethodInvocation();
    setEnableStateExpr.setExpression(ast.newSimpleName(resultVarName));
    AssociationEnableState state =
        association.getForeignKeyConstraintType() == ForeignKeyConstraintType.Forbid
            ? AssociationEnableState.Disabled
            : AssociationEnableState.Enabled;
    QualifiedName enableStateValue =
        ast.newQualifiedName(
            ast.newName("AssociationEnableState"),
            ast.newSimpleName(state.toString()));
    addImport(AssociationEnableState.class.getTypeName());
    setEnableStateExpr.setName(ast.newSimpleName("setEnableState"));
    setEnableStateExpr.arguments().add(enableStateValue);
    ExpressionStatement expressionStatement3=ast.newExpressionStatement(setEnableStateExpr);
    rez.statements().add(expressionStatement3);

    MethodInvocation setSourceColumnExpr = ast.newMethodInvocation();
    setSourceColumnExpr.setExpression(ast.newSimpleName(resultVarName));
    StringLiteral sourceColumnValue = ast.newStringLiteral();


    sourceColumnValue.setLiteralValue(association.getKeyCollection().get(0).getSourceElementDisplay());
    setSourceColumnExpr.setName(ast.newSimpleName("setPrivateSourceColumn"));
    setSourceColumnExpr.arguments().add(sourceColumnValue);
    ExpressionStatement expressionStatement4=ast.newExpressionStatement(setSourceColumnExpr);
    rez.statements().add(expressionStatement4);

    ReturnStatement returnStatement = ast.newReturnStatement();
    returnStatement.setExpression(ast.newSimpleName(resultVarName));
    rez.statements().add(returnStatement);

    return rez;
  }

  @Override
  protected boolean hasSetMethod() {
    return false;
  }

  private String[] parseRef(GspAssociation assocaition) {
    GspMetadata refMd = null; // 获取关联BE的元数据
    try {
      refMd =parentContext.getApiGenContext().getCefGenContext().getMetadata(assocaition.getRefModelPkgName(), assocaition.getRefModelID());
    } catch (Exception e) {
      throw new RuntimeException("关联元数据"+assocaition.getRefModelCode()+"获取失败", e);
    }

    GspBusinessEntity beEntity =
        (GspBusinessEntity)
            ((refMd.getContent() instanceof GspBusinessEntity)
                ? refMd.getContent()
                : null); // 关联的BE
    if(beEntity == null){
      throw new RuntimeException("关联元数据"+assocaition.getRefModelCode()+"获取失败,当前获取到的类型是"+refMd.getContent().getClass().getName());
    }

    String befConfig = beEntity.getGeneratedConfigID(); // 关联的BE的BefConfig
    String nodeCode = assocaition.getRefObjectCode(); // 关联的BE的节点编号
    if (DotNetToJavaStringHelper.isNullOrEmpty(nodeCode)) {
      nodeCode = beEntity.getMainObject().getCode();
    }
    // string nodeCode = beEntity.getMainObject().getCode();
    String mainCode = beEntity.getMainObject().getCode();
    return new String[] {befConfig, nodeCode, mainCode};
  }
}
